import fetch from 'dva/fetch';
/*
import { device } from './utils';
*/

function loginRedirect(){
  /*if (device.app) {
    const responseAppParam = request("/mall/user/app/param/get",{_CallBackUrl: location.origin + "/h5.html#/index?deviceType=app"});
    if(responseAppParam){
      let cfg = {
        _isThirdLogin: res.result._isThirdLogin,
        params: res.result.params
      };
      // Fw.sendNewThirdLoginReq(cfg);
    }
  }else{
    console.log('未登录');
    window.location.replace(basepath + "/wx/main");
  }*/
}

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  
  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  
  const defaultOptions = {
    credentials: 'include',
    mode: "cors",
  };
  const newOptions = { ...defaultOptions, ...options };
  
  if(!newOptions.isForm){
    newOptions.headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
      ...newOptions.headers,
    };
    
    newOptions.body = JSON.stringify(newOptions.body);
  }
  return fetch('https://m.mafengwo.cn' + url, newOptions)
    .then(checkStatus)
    .then(parseJSON)
    .then(data=>{
      if(data){
        return data.body
      }else{
        /*if(data.msg=='用户没有登录！'){
		  loginRedirect();
		}else{
		  window.alertFalse = alert('错误', `请求错误 ${data.msg}`, [
			{ text: '取消', onPress: () => console.log('cancel'), style: 'default' },
			{ text: '确认', onPress: () => console.log('ok') },
		  ]);

		}*/
      }
    })
    .catch(err => ({ err }));
}
